package com.spring.sunflower.dialog

import android.app.Activity
import android.content.Intent
import android.os.CountDownTimer
import android.os.Handler
import android.text.TextUtils
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.lxj.xpopup.core.PositionPopupView
import com.makeramen.roundedimageview.RoundedImageView
import com.spring.sunflower.R
import com.spring.sunflower.anchor.PersonalDetailActivity
import com.spring.sunflower.bean.LiveApplyChatBean
import com.spring.sunflower.constant.Constant
import com.spring.sunflower.conversation.ChatVideoActivity
import com.spring.sunflower.data.RequestDataSource
import com.spring.sunflower.event.LuckyMatchEvent
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.observers.DisposableObserver
import io.reactivex.rxjava3.schedulers.Schedulers

/**
 * Created by Kevin on 2021/11/17<br/>
 *
 * Describe:<br/>
 */
class LuckyMatchDialog(context: Activity, var data: LuckyMatchEvent, val type: String) :
    PositionPopupView(context) {
    private var avatar: RoundedImageView? = null
    private var nickname: TextView? = null
    private var level: TextView? = null
    private var location: TextView? = null
    private var age: TextView? = null
    private var tvDone: TextView? = null
    private var close: ImageView? = null
    private var tvTime: TextView? = null
    private var llDone: LinearLayout?=null
    val countDownTimer: CountDownTimer by lazy {
        object : CountDownTimer(15000, 1000) {
            override fun onTick(millisUntilFinished: Long) {
                tvTime?.text = "${millisUntilFinished / 1000}s"
            }

            override fun onFinish() {
                applyChat()
                if (isShow) {
                    dismiss()
                }
            }
        }
    }
    val r = Runnable { if (isShow) dismiss() }
    private val mHandler by lazy { Handler() }
    override fun getImplLayoutId(): Int {
        return R.layout.dialog_lucky_match
    }

    override fun onCreate() {
        super.onCreate()
        avatar = findViewById(R.id.rivAvatar)
        nickname = findViewById(R.id.tvNickname)
        level = findViewById(R.id.tvLevel)
        location = findViewById(R.id.tvLocation)
        age = findViewById(R.id.tvAge)
        tvDone = findViewById(R.id.tvDone)
        close = findViewById(R.id.ivClose)
        tvTime = findViewById(R.id.tvTime)
        llDone=findViewById(R.id.llDone)
        Glide.with(context)
            .load(data.photo)
            .placeholder(R.drawable.ic_placeholder)
            .into(avatar!!)
        nickname?.text = data.nickname
        level?.text = "匹配度${data.matchDegree}%"
        location?.text = if (TextUtils.isEmpty(data.city)) "火星" else data.city
        age?.text = "${data.age}岁"
        var timeTotal = 5
        tvDone?.let {
            if (type == "30") {
                it.text = "视频聊天"
                tvTime?.visibility = VISIBLE
                countDownTimer.start()
            } else {
                it.text = "立即查看"
                tvTime?.visibility = GONE
            }
        }
        llDone?.setOnClickListener {
            if (type == "30") {
                countDownTimer.cancel()
                applyChat()
            } else {
                val intent = Intent(context, PersonalDetailActivity::class.java)
                intent.putExtra(Constant.KEY_TARGET_ID, data.anchorId.toString())
                context.startActivity(intent)
            }
            dismiss()
        }
        close?.setOnClickListener {
            dismiss()
        }
        if (type == "25") {
            mHandler.postDelayed(r, 10000)
        }
    }

    override fun onDismiss() {
        super.onDismiss()
        mHandler.removeCallbacks(r)
        countDownTimer.cancel()
    }

    fun applyChat() {
        if (TextUtils.isEmpty(data.anchorId.toString())) {
            dismiss()
            ToastUtils.showShort("呼叫失败~")
            return
        }
        if (!XXPermissions.isGranted(
                context,
                Permission.RECORD_AUDIO
            ) || !XXPermissions.isGranted(context, Permission.CAMERA)
        ) {
            DialogManager.getInstance().showPermissionIntroDialog(context,
                arrayOf<String>(
                    context.getString(R.string.permission_audio_title),
                    context.getString(R.string.permission_camera_title)
                ),
                arrayOf<String>(
                    context.getString(R.string.permission_audio_desc),
                    context.getString(R.string.permission_camera_desc)
                ), object : OnPermissionIntroClickListener {
                    override fun onClickOK() {
                        XXPermissions.with(context)
                            .permission(Permission.RECORD_AUDIO, Permission.CAMERA)
                            .request(object : OnPermissionCallback {
                                override fun onGranted(
                                    permissions: List<String>,
                                    all: Boolean
                                ) {
                                    if (all) {
                                        applyChatVideo()
                                    } else {
                                        DialogManager.getInstance()
                                            .showPermissionIntroDialog(
                                                context,
                                                context.getString(R.string.permission_denied_title),
                                                "无法正常进行视频通话",
                                                null
                                            )
                                    }
                                }

                                override fun onDenied(
                                    permissions: List<String>,
                                    never: Boolean
                                ) {
                                    DialogManager.getInstance()
                                        .showPermissionIntroDialog(
                                            context,
                                            context.getString(R.string.permission_denied_title),
                                            "无法正常进行视频通话",
                                            null
                                        )
                                }
                            })
                    }

                })

        } else {
            applyChatVideo()
        }
    }

    fun applyChatVideo() {
        val anchorId = data.anchorId
        val instance = RequestDataSource.getInstance()
        val observable = instance.liveApplyChatAnchor(anchorId.toString())
        observable.subscribeOn(Schedulers.io())
            .subscribeOn(AndroidSchedulers.mainThread())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : DisposableObserver<LiveApplyChatBean>() {
                override fun onNext(t: LiveApplyChatBean) {
                    val intent = Intent(context, ChatVideoActivity::class.java)
                    intent.putExtra(Constant.VIDEO_CALL_SELF_DIAL, true)
                    intent.putExtra(Constant.VIDEO_CALL_OTHER_ID, anchorId)
                    intent.putExtra(Constant.VIDEO_CALL_OTHER_FACE_URL, data.photo)
                    intent.putExtra(Constant.VIDEO_CALL_OTHER_NICKNAME, data.nickname)
                    intent.putExtra(Constant.VIDEO_CALL_SHOW, false)
                    context.startActivity(intent)
                }

                override fun onError(e: Throwable?) {
                    ToastUtils.showShort(e?.message)
                }

                override fun onComplete() {
                    if (isShow) {
                        dismiss()
                    }
                }
            })
    }

}